/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.locationroom.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.locationroom.entity.BizLocationRoom;
import vip.xiaonuo.biz.modular.locationroom.mapper.BizLocationRoomMapper;
import vip.xiaonuo.biz.modular.locationroom.param.*;
import vip.xiaonuo.biz.modular.locationroom.service.BizLocationRoomService;
import vip.xiaonuo.biz.modular.locationroom.vo.BizLocationRoomPageResp;
import vip.xiaonuo.biz.modular.relation.entity.BizRelation;
import vip.xiaonuo.biz.modular.relation.enums.BizRelationCategoryEnum;
import vip.xiaonuo.biz.modular.relation.service.BizRelationService;
import vip.xiaonuo.common.exception.CommonException;

import java.util.List;

/**
 * 房间Service接口实现类
 *
 * @author kongxm
 * @date 2022/11/06 22:26
 **/
@Service
public class BizLocationRoomServiceImpl extends ServiceImpl<BizLocationRoomMapper, BizLocationRoom> implements BizLocationRoomService {

    @Autowired
    private BizRelationService bizRelationService;

    @Override
    public Page<BizLocationRoomPageResp> page(BizLocationRoomPageParam bizLocationRoomPageParam) {
        return getBaseMapper()
                .page(Page.of(bizLocationRoomPageParam.getCurrent(), bizLocationRoomPageParam.getSize()),
                        bizLocationRoomPageParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(BizLocationRoomAddParam param) {
        // check data. 保证“区域”+“楼宇”+房间的唯一性。
        long existCount = getBaseMapper().selectCount(new LambdaQueryWrapper<BizLocationRoom>()
                .eq(BizLocationRoom::getAreaId, param.getAreaId())
                .eq(BizLocationRoom::getBuildingId, param.getBuildingId())
                .eq(BizLocationRoom::getName, param.getName()));
        Assert.isTrue(existCount == 0, "区域 + 楼宇 + 房间, 重复");
        BizLocationRoom bizLocationRoom = BeanUtil.toBean(param, BizLocationRoom.class);
        this.save(bizLocationRoom);
        this.saveRelations(bizLocationRoom.getId(),
                param.getInChargeUserId(),
                param.getSafetyUserId());
    }

    @Override
    public void edit(BizLocationRoomEditParam param) {
        // check data. 保证“区域”+“楼宇”+房间的唯一性。
        long existCount = getBaseMapper().selectCount(new LambdaQueryWrapper<BizLocationRoom>()
                .ne(BizLocationRoom::getId, param.getId())
                .eq(BizLocationRoom::getAreaId, param.getAreaId())
                .eq(BizLocationRoom::getBuildingId, param.getBuildingId())
                .eq(BizLocationRoom::getName, param.getName()));
        Assert.isTrue(existCount == 0, "区域 + 楼宇 + 房间, 重复");
        BizLocationRoom bizLocationRoom = this.queryEntity(param.getId());
        BeanUtil.copyProperties(param, bizLocationRoom);
        this.updateById(bizLocationRoom);
        this.saveRelations(bizLocationRoom.getId(),
                param.getInChargeUserId(),
                param.getSafetyUserId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizLocationRoomIdParam> bizLocationRoomIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(bizLocationRoomIdParamList, BizLocationRoomIdParam::getId));
        bizLocationRoomIdParamList.forEach(item -> bizRelationService.remove(new LambdaQueryWrapper<BizRelation>()
                .eq(BizRelation::getObjectId, item.getId())));
    }

    @Override
    public BizLocationRoom detail(BizLocationRoomIdParam bizLocationRoomIdParam) {
        return this.queryEntity(bizLocationRoomIdParam.getId());
    }

    @Override
    public BizLocationRoom queryEntity(String id) {
        BizLocationRoom bizLocationRoom = this.getById(id);
        if (ObjectUtil.isEmpty(bizLocationRoom)) {
            throw new CommonException("房间不存在，id值为：{}", id);
        }
        return bizLocationRoom;
    }

    @Override
    public List<BizLocationRoom> list(BizLocationRoomListParam bizLocationRoomListParam) {
        return getBaseMapper().list(bizLocationRoomListParam);
    }

    private void saveRelations(String roomId, String inChargeUserId, String safetyUserId) {
        if (StringUtils.isNotEmpty(inChargeUserId)) {
            bizRelationService.saveRelationWithClear(roomId, inChargeUserId,
                    BizRelationCategoryEnum.BIZ_RELATION_ROOM_AND_IN_CHARGE_USER.getValue());
        }
        if (StringUtils.isNotEmpty(safetyUserId)) {
            bizRelationService.saveRelationWithClear(roomId, safetyUserId,
                    BizRelationCategoryEnum.BIZ_RELATION_ROOM_AND_SAFETY_USER.getValue());
        }
    }
}
